
package controllers;

import java.util.ArrayList;
import java.util.List;

import models.spider.actor.CrawlerService;
import models.spider.config.AAA;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.search.jpa.FullTextQuery;

import play.data.Form;
import play.db.jpa.Transactional;
import play.mvc.Result;

/**
 * 
 * @author laurent@opprecht.info
 */
public class Search extends Application {

    public static class TextEntry {

        public String text;
    }

    public static CrawlerService crawler() {
        CrawlerService result = new CrawlerService(new AAA());
        return result;
    }

    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public static Result index() {
    	if(Authentication.isAdmin()) {
	        Form<TextEntry> form = play.data.Form.form(TextEntry.class).bindFromRequest();
	
	        List<models.aaa.Asset> items = new ArrayList<>();
	        int size = 0;
	
	        String text = form.get().text;
	        if (StringUtils.isEmpty(text)) {
	            return ok(views.html.search.index.render(form, items, 0));
	        }
	
	        models.aaa.Asset actor = getUser().getActor();
	        FullTextQuery query = models.aaa.Asset.find.with(text, actor);
	        if (query == null) {
	            flash("warning", "no result found");
	            return ok(views.html.search.index.render(form, items, 0));
	        }
	
	        size = query.getResultSize();
	        items = query.setMaxResults(20).getResultList();
	        if (items.size() == 0) {
	            flash("warning", "no result found");
	        }
	        
	        for(models.aaa.Asset item: items) System.out.println(item.getLid());
	
	        return ok(views.html.search.index.render(form, items, size));
	    }
		return redirect(routes.Authentication.login());
    }
}
